package socket

import (
	"net"
	"strconv"
	"strings"
	"time"
)

//ListenLongAdress socket监听长连接
func ListenLongAdress(port string) {
	tcpAdress, err := net.ResolveTCPAddr("tcp", port)
	if err != nil {
		return
	}
	listen, err := net.ListenTCP("tcp", tcpAdress)
	if err != nil {
		return
	}
	defer listen.Close()
	for {
		conn, err := listen.Accept()
		if err != nil {
			continue
		}
		go handldLongFunc(conn)
	}
}

func handldLongFunc(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
	defer conn.Close()

	req := make([]byte, 128)
	for {
		connLen, err := conn.Read(req)
		if err != nil {
			break
		}
		if connLen == 0 {
			break
		} else if strings.TrimSpace(string(req[:connLen])) == "timestamp" {
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}

		req = make([]byte, 128) // clear last read content
	}
}
